<template>
  <div :class="className" ref="chartVal" :style="{ width: width, height: height }"></div>
</template>

<script setup>
import { ref, reactive, onMounted, onBeforeUnmount, watch, nextTick } from 'vue';
import * as echarts from 'echarts';

const props = defineProps({
  className: {
    type: String,
    default: 'chart'
  },
  width: {
    type: String,
    default: '100%'
  },
  height: {
    type: String,
    default: '230px'
  },
  chartData: {
    type: Object,
    default: () => {}
  }
});

const chartVal = ref(null);
let chart = null;

watch(() => 
  props.chartData, 
  (newVal) => {
    nextTick(() => {
      initChart();
    })
  },
  {
    deep: true,
    immediate: true
  }
);

onMounted(() => {
  window.addEventListener('resize', initChartResize);
});

onBeforeUnmount(() => {
  window.removeEventListener('resize', initChartResize);
  if(chart) {
    chart.dispose();
  }
})

const initChart = () => {
  let { xData, yData } = props.chartData;
  chart = echarts.init(chartVal.value, 'macarons');
  chart.clear();
  chart.setOption({
    tooltip: {
      trigger: 'axis',
    },
    legend: {
      icon: 'rect',
      itemWidth: 12,
      itemHeight: 12,
      itemGap: 10,
      // data: xData,
      x: 'right',
      y: '5',
      textStyle: {
        fontSize: 14,
        color: '#fff'
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '15%',
      top: '15%',
      containLabel: true
    },
    xAxis: [{
      type: 'category',
      boundaryGap: true,
      axisLine: {
        lineStyle: {
          color: '#3F6DA0'
        }
      },
      axisTick: {
        show: false
      },
      axisLabel: {
        margin: 10,
        fontSize: 14,
        color: '#fff'
      },
      data: xData
    }],
    yAxis: [{
      type: 'value',
      nameTextStyle: {
        fontSize: 14,
        color: '#fff',
        padding: [0, 0, 0, -25]
      },
      axisTick: {
        show: false
      },
      axisLine: {
        show: false,
        lineStyle: {
          color: '#57617B'
        }
      },
      axisLabel: {
        margin: 10,
        fontSize: 14,
        color: '#fff'
      },
      splitLine: {
        lineStyle: {
          type: 'dashed',
          color: '#0388FB'
        }
      }
    }],
    series:[{
      name: '销量',
      type: 'bar',
      barWidth: 10,
      barGap: 1,
      itemStyle: {
        color: '#0388FB',
        borderRadius: [5, 5, 0, 0]
      },
      data: yData
    }]
  })
};

const initChartResize = () => {
  if(chart) {
    chart.resize();
  }
}

</script>

<style scoped>

</style>